//
//  MerchantManageVC.swift
//  kxf
//  商户管理
//  Created by Mac on 2024/3/23.
//

import Foundation
import MJRefresh
import MCToast

class MerchantManageVC: WHBaseViewVC {
    
    var pageNum =  1
    var pageSize = 5
    var phone = ""
    
    var dataSourceArray = NSMutableArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        sendDataListRequest()
    }
    lazy var searchVm : SearchVM = {
        let vm = SearchVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight() + kFitWidth(10), width: 0, height: 0))
        vm.textField.placeholder = "请输入手机号搜索"
        vm.textField.keyboardType = .asciiCapable
        vm.backgroundColor = WHColor_16(colorStr: "EFEFEF")
        vm.searchBlock = {()in
            self.phone = self.searchVm.textField.text ?? ""
            self.pageNum = 1
            self.sendDataListRequest()
        }
        return vm
    }()
    
    lazy var tableView : UITableView = {
        let vi = UITableView.init(frame: CGRect.init(x: 0, y: self.searchVm.frame.maxY+kFitWidth(8), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(self.searchVm.frame.maxY+kFitWidth(8))), style: .plain)
        vi.delegate = self
        vi.dataSource = self
        vi.separatorStyle = .none
        vi.backgroundColor = .COLOR_LIGHT_GREY
        
        vi.register(MercManageTableVIewCell.classForCoder(), forCellReuseIdentifier: "MercManageTableVIewCell")
        
        vi.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.pageNum = 1
            self.sendDataListRequest()
        })

        vi.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            self.pageNum += 1
            self.sendDataListRequest()
        })
        if #available(iOS 11.0, *) {
            vi.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        
        return vi
    }()
    lazy var emptyView : EmptyViewWithBtn = {
        let emptyViewT = EmptyViewWithBtn.init(frame: CGRect.zero)
        emptyViewT.isHidden = true
        emptyViewT.contentLabel.text = "还没有记录~"
        
        return emptyViewT
    }()
}

extension MerchantManageVC{
    func initUI() {
        initNavi(titleStr: "商户管理")
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        
        view.addSubview(searchVm)
        view.addSubview(tableView)
        tableView.addSubview(emptyView)
        emptyView.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: self.tableView.frame.height*0.5)
    }
}

extension MerchantManageVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        emptyView.isHidden = dataSourceArray.count > 0 ? true : false
        return dataSourceArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MercManageTableVIewCell") as! MercManageTableVIewCell
        
        let dict = self.dataSourceArray[indexPath.row]as? NSDictionary ?? [:]
        
        cell.updateUI(dict: dict)
//        cell.updateUIForMerc(dict: dict)
//        
//        cell.manageSettleBlock = {()in
//            let vc = SetRateVC()
////            vc.isMerc = true
//            vc.phone = dict["phone"]as? String ?? ""
//            self.navigationController?.pushViewController(vc, animated: true)
//        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return kFitWidth(138)
        return kFitWidth(333)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let dict = self.dataSourceArray[indexPath.row]as? NSDictionary ?? [:]
        
//        if dict["posStatus"]as? Int ?? -5 == 4{
//            self.sendGetMsgRequset(tel: "\(dict["phone"]as? String ?? "")")
            
            let vc = MerchantDetailVC()
            vc.msgDict = dict
            self.navigationController?.pushViewController(vc, animated: true)
//        }
    }
}

extension MerchantManageVC{
    func sendDataListRequest() {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_posUserManage_list)?pageSize=\(pageSize)&pageNum=\(pageNum)&phone=\(phone)") { responseObject in
            MCToast.mc_remove()
            DLLog(message: "\(responseObject)")
            self.tableView.mj_footer!.endRefreshing()
            self.tableView.mj_header!.endRefreshing()
            
            if responseObject["code"]as? Int ?? 0 == 200 {
                let dataObj = responseObject["data"]as? NSDictionary ?? [:]
                let dataArr = dataObj["list"]as? NSArray ?? []
                
                if self.pageNum == 1{
                    self.dataSourceArray.removeAllObjects()
                }
                self.dataSourceArray.addObjects(from: dataArr as! [Any])
                // 提示没有更多数据
                if dataArr.count < self.pageSize {
                    self.tableView.mj_footer!.endRefreshingWithNoMoreData()
                }
                
                self.tableView.reloadData()
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "网络异常")", viewController: self)
            }
        }
    }
    func sendAuthenMsgVerifyRequest(phone:String) {
        let urlString = "\(URL_authen_msg_verify)?tel=\(phone)"
        WHNetworkUtil.shareManager().GET(urlString: urlString,vc:self) { response in
            DLLog(message: "\(response)")
            if response["code"]as? Int ?? -1 == 200{
                let data = response["data"]as? NSDictionary ?? [:]
                if data["merchantType"]as? String ?? "" == "0"{
                    AuthenCompanyMsgModel.shareInstance.refreshMsg(dict: data)
                    AuthenCompanyMsgModel.shareInstance.posChannel = UserModel.shared.posChannel
                    
                    if AuthenCompanyMsgModel.shareInstance.posChannel == "fy"{
                        let vc = AuthenCompanyFYVC()
                        vc.isUpdate = true
                        vc.isRead = true
                        self.navigationController?.pushViewController(vc, animated: true)
                    }else{
                        let vc = AuthenCompanyVC()
                        vc.isUpdate = true
                        vc.isRead = true
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }else if data["merchantType"]as? String ?? "" == "1"{
                    AuthenMiniMsgModel.shareInstance.refreshMsg(dict: data)
                    AuthenMiniMsgModel.shareInstance.posChannel = UserModel.shared.posChannel
                    let vc = AuthenMiniVC()
                    vc.isUpdate = true
                    vc.isRead = true
                    self.navigationController?.pushViewController(vc, animated: true)
                }else if data["merchantType"]as? String ?? "" == "2"{
                    AuthenCompanyMsgModel.shareInstance.refreshMsg(dict: data)
                    AuthenCompanyMsgModel.shareInstance.posChannel = UserModel.shared.posChannel
                    let vc = AuthenGeTiVC()
                    vc.isUpdate = true
                    vc.isRead = true
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }else{
                self.presentAlertVcNoAction(title: "\(response["message"]as? String ?? "网络请求错误")", viewController: self)
            }
        }
    }
    func sendGetMsgRequset(tel:String) {
        MCToast.mc_loading()
        let urlString = "\(URL_authen_msg_query)?tel=\(tel)"
        
        WHNetworkUtil.shareManager().GET(urlString: urlString,vc:self) { responseObject in
            DLLog(message: "\(responseObject)")
            
            let dataObj = responseObject["data"]as? NSDictionary ?? [:]
            UserModel.shared.posChannel = dataObj["posChannel"]as? String ?? "ys"
            if dataObj["merchantType"]as? String ?? "" == "0" {
                AuthenCompanyMsgModel.shareInstance.refreshMsg(dict: responseObject["data"]as? NSDictionary ?? [:])
                
                if AuthenCompanyMsgModel.shareInstance.posChannel == "fy"{
                    let vc = AuthenCompanyFYVC()
                    vc.isUpdate = true
                    vc.isRead = true
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    let vc = AuthenCompanyVC()
                    vc.isUpdate = true
                    vc.isRead = true
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }else if dataObj["merchantType"]as? String ?? "" == "1" {
                AuthenMiniMsgModel.shareInstance.refreshMsg(dict: responseObject["data"]as? NSDictionary ?? [:])
                let vc = AuthenMiniVC()
                vc.isUpdate = true
                vc.isRead = true
                self.navigationController?.pushViewController(vc, animated: true)
            }else if dataObj["merchantType"]as? String ?? "" == "2" {
                AuthenCompanyMsgModel.shareInstance.refreshMsg(dict: responseObject["data"]as? NSDictionary ?? [:])
                let vc = AuthenGeTiVC()
                vc.isUpdate = true
                vc.isRead = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
}
